﻿using AutoMapper;
using MediatR;
using NPOI.SS.Formula.Functions;
using ProductionManagement.Application.Command.PreProductionCommand;
using ProductionManagement.Domain.ProductionDomain;
using ProductionManagement.Infrstructre.lmp;
using ProductionManagement.Infrstructre.lnterface;
using SqlSugar;

namespace ProductionManagement.Application.CommandHandler.PreProductionCommandHandler
{
    /// <summary>
    /// 修改预生产计划命令处理器
    /// </summary>
    public class PreProductionUpdCommandHandler : IRequestHandler<PreProductionUpdCommand, int>
    {
        private readonly IPreProducsRepository _preProducsRep;
        private readonly IPreProductionRepository _preProductionRep;
        private readonly ISqlSugarClient db;
        private readonly IMapper _mapper;

        public PreProductionUpdCommandHandler(IPreProducsRepository preProducsRep, IPreProductionRepository preProductionRep, ISqlSugarClient db, IMapper mapper)
        {
            this._preProducsRep = preProducsRep;
            this._preProductionRep = preProductionRep;
            this.db = db;
            this._mapper = mapper;
        }

        public async Task<int> Handle(PreProductionUpdCommand request, CancellationToken cancellationToken)
        {
            // 开启事务
            db.Ado.BeginTran();
            try
            {
                //修改采购退货
                var se = await db.Queryable<PreProduction>()
                                 .Where(c => c.PreProductionId == request.updDto.PreProductionId)
                .FirstAsync();

                var preProduction = _mapper.Map<PreProduction>(request.updDto);
                int Item = await _preProductionRep.UpdAsync(preProduction);


                //删除采购退货中的数据
                var itemsToDelete = await db.Queryable<PreProducs>()
                                  .Where(c => c.PPDocuNumber == se.PPDocuNumber)
                                  .ToListAsync();
                foreach (var item in itemsToDelete)
                {
                    await _preProducsRep.DelRange(new List<PreProducs> { item });
                }


                foreach (var subpiece in request.updDto.FanDto)
                {
                    PreProducs items = new PreProducs();
                    items.PreProducsId = subpiece.PreProducsId;
                    items.PPDocuNumber = preProduction.PPDocuNumber;
                    items.ProductId = subpiece.ProductId;
                    items.PPsNum = subpiece.PPsNum;
                    items.PPsDeliveryDate = subpiece.PPsDeliveryDate;
                    items.PNumber = subpiece.PNumber;
                    items.PName = subpiece.PName;
                    items.PSpec = subpiece.PSpec;
                    items.PUnit = subpiece.PUnit;
                    items.PPsSmark = subpiece.PPsSmark;
                    items.AddName = preProduction.AddName;
                    items.AddTime = preProduction.AddTime;
                    items.UpdName = preProduction.UpdName;
                    items.UpdTime = preProduction.UpdTime;
                    items.Office_Id=preProduction.Office_Id;
                    items.User_Id=preProduction.User_Id;
                    await _preProducsRep.AddAsync(items);
                }
                // 提交事务
                db.Ado.CommitTran();
                return 1;
            }
            catch (Exception ex)
            {
                // 捕获异常并回滚事务
                db.Ado.RollbackTran();
                // 可以记录日志以便调试
                throw new Exception("事务失败，已回滚所有操作", ex);
            }
        }
    }
}
